<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>音频可视化</title>
</head>
<body>
<input type="file" id="audioInput" accept="audio/*">
<canvas id="canvas"></canvas>

<script>
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    let audioContext;
    let source;
    let analyser;
    let bufferLength;
    let dataArray;

    function handleFiles(event) {
        const files = event.target.files;
        const file = files[0];
        const url = URL.createObjectURL(file);
        const audio = new Audio();
        audio.src = url;
        audio.crossOrigin = 'anonymous';

        const playPromise = audio.play();
        if (playPromise !== undefined) {
            playPromise.then(() => {
                // 音频播放成功
                audioContext = new AudioContext();
                source = audioContext.createMediaElementSource(audio);
                analyser = audioContext.createAnalyser();
                bufferLength = analyser.frequencyBinCount;
                dataArray = new Uint8Array(bufferLength);
                source.connect(analyser);
                analyser.connect(audioContext.destination);
                draw();
            }).catch(() => {
                // 音频播放失败
                console.log('Failed to play audio.');
            });
        }
    }

    function draw() {
        requestAnimationFrame(draw);
        analyser.getByteFrequencyData(dataArray);
        ctx.fillStyle = 'rgb(0, 0, 0)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        const barWidth = (canvas.width / bufferLength) * 2.5;
        let barHeight;
        let x = 0;
        for (let i = 0; i < bufferLength; i++) {
            barHeight = dataArray[i];
            ctx.fillStyle = 'rgb(' + (barHeight + 100) + ',50,50)';
            ctx.fillRect(x, canvas.height - barHeight / 2, barWidth, barHeight / 2);
            x += barWidth + 1;
        }
    }

    document.getElementById('audioInput').addEventListener('change', handleFiles);
</script>
</body>
</html>
